import Vue from 'vue';
import iView from 'view-design';
import VueI18n from 'vue-i18n';
import en from 'view-design/dist/locale/en-US';
import zh from 'view-design/dist/locale/zh-CN';
import US from './en';
import CN from './zh'
import GoogleTranslateService from '@/plugins/googleTranslate'

Vue.use(VueI18n);
Vue.locale = () => {};

const messages = {
  en: Object.assign(US, en),
  zh: Object.assign(CN, zh)
};

const language = (navigator.language || navigator.browserLanguage).toLowerCase()
const i18n = new VueI18n({
  locale: localStorage.getItem("locale") || language,
  messages,
  // 添加缺失翻译的回调
  missing: async (locale, key, vm, values) => {
    // 如果找不到翻译，使用谷歌翻译
    if (locale !== 'zh' && messages.zh[key]) {
      const translated = await GoogleTranslateService.translateText(
        messages.zh[key], 
        locale === 'en' ? 'en' : locale
      )
      // 动态添加翻译
      i18n.setLocaleMessage(locale, {
        ...i18n.getLocaleMessage(locale),
        [key]: translated
      })
      return translated
    }
    return key
  }
});

Vue.use(iView, { 
  i18n: (key, value) => i18n.t(key, value)
})

export default i18n